import React, { useState, useEffect } from 'react';
import { Form, Input, Spin, DatePicker, Select, message } from 'antd';
import { withRouter, connect } from 'umi';
import moment from 'moment';
import { isSuccess } from '@/utils/request';
import { queryEmployeeList } from '@/services/salaryManage/salaryCommon';
import { queryDictList } from '@/services/salaryManage/salaryCalculate';

import BaseSettingProvider from '@/pages/SalaryManage/components/BaseSettingProvider';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import LimitInput from '@/components/LimitInput';
import keyBy from 'lodash/keyBy';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import ValidatorTable from './ValidatorTable';
import style from './index.less';

const { Item } = Form;

const { RangePicker } = DatePicker;
/**
 * 特殊人员薪资审批套件
 * @returns {*}
 */

const SalaryProcessApply = props => {
    const { form, formValueMap, user, location, decimalPlaces, dataSource } = props;
    const { getFieldDecorator } = form;
    const [loading, setLoading] = useState(false);
    const [workOption, setWorkOption] = useState([]);
    const [employeeList, setEmployeeList] = useState([]);
    const { query } = location;
    const { id } = query;

    const childConfig = dataSource?.children?.length > 0 ? dataSource.children : [];
    const childrenConfigMap = keyBy(childConfig, 'formId');
    const summaryConfig = childrenConfigMap.summary;
    const organizationNameConfig = childrenConfigMap.organizationName;

    const isApply = !formValueMap && !!id;

    const [pageModel, setPageModel] = useState(
        formValueMap?.salaryProcessApplyModel || {
            employees: [],
            orgCode: user.companyId,
            companyName: user.companyName,
            salaryConfigType: undefined,
            approver: user.employeeCode,
            remark: '',
            startDateTime: '',
            endDateTime: ''
        }
    );

    const setFieldValue = (filedName, fieldValue) => {
        setPageModel({ ...pageModel, [filedName]: fieldValue });
    };

    useEffect(() => {
        setLoading(true);
        try {
            queryDictList('flowTypeOptions')
                .then(response => {
                    if (isSuccess(response)) {
                        setWorkOption(response.data?.flowTypeOptions || []);
                    } else {
                        message.error(response.msg);
                    }
                })
                .finally(() => {
                    setLoading(false);
                });

            if (isApply) {
                queryEmployeeList({
                    organizationCode: user?.companyId
                }).then(res => {
                    const data = isSuccess(res) ? res.data : [];
                    setEmployeeList(data);
                });
            }
        } catch (error) {
            console.log(error);
            setLoading(false);
        }
    }, [isApply, user]);

    // 切换日期范围
    const changeDate = val => {
        if (val && val.length) {
            setPageModel({
                ...pageModel,
                startDateTime: moment(val[0]).format('YYYY-MM-DD'),
                endDateTime: moment(val[1]).format('YYYY-MM-DD')
            });
        } else {
            setPageModel({ ...pageModel, startDateTime: '', endDateTime: '' });
        }
    };

    useEffect(() => {
        if (formValueMap?.salaryProcessApplyModel) {
            setPageModel(formValueMap?.salaryProcessApplyModel);
        }
    }, [formValueMap]);

    return (
        <Spin spinning={loading}>
            <BaseSettingProvider organizationCode={user?.companyId}>
                <div>
                    {organizationNameConfig ? (
                        <Form.Item
                            label={organizationNameConfig.label}
                            key={organizationNameConfig.formId}
                            style={{ display: organizationNameConfig?.inRenderDom === false ? 'none' : 'block' }}
                        >
                            {getFieldDecorator(organizationNameConfig?.formId, {
                                rules: organizationNameConfig?.rules,
                                initialValue: pageModel?.companyName
                            })(<AutoRenderComponent form={form} config={organizationNameConfig} />)}
                        </Form.Item>
                    ) : null}

                    {/* 流程名称 */}
                    {summaryConfig ? (
                        <Form.Item
                            label={summaryConfig.label}
                            key={summaryConfig.formId}
                            style={{ display: summaryConfig?.inRenderDom === false ? 'none' : 'block' }}
                        >
                            {getFieldDecorator(summaryConfig?.formId, {
                                rules: summaryConfig?.rules,
                                initialValue:
                                    formValueMap?.[summaryConfig.formId] ?? summaryConfig?.options?.initialValue
                            })(<AutoRenderComponent form={form} config={summaryConfig} />)}
                        </Form.Item>
                    ) : null}

                    {getFieldDecorator('salaryProcessApplyModel', {
                        initialValue: pageModel
                    })(<Input type="hidden" />)}
                    <Item label="行政机构">{pageModel?.companyName}</Item>
                    <Item label="薪资类型">
                        {getFieldDecorator('salaryConfigType', {
                            initialValue: pageModel?.salaryConfigType,
                            rules: [
                                {
                                    required: true,
                                    message: '请选择薪资类型'
                                }
                            ]
                        })(
                            <Select
                                style={{ maxWidth: '300px' }}
                                placeholder="请选择"
                                disabled={!isApply}
                                onChange={val => setFieldValue('salaryConfigType', val)}
                            >
                                {workOption.map(item => (
                                    <Select.Option key={item.key} value={item.key}>
                                        {item.value}
                                    </Select.Option>
                                ))}
                            </Select>
                        )}
                    </Item>
                    <Item label="日期范围">
                        <RangePicker
                            format="YYYY-MM-DD"
                            disabled={!isApply}
                            value={
                                pageModel.startDateTime && pageModel.endDateTime
                                    ? [moment(pageModel.startDateTime), moment(pageModel.endDateTime)]
                                    : null
                            }
                            onChange={val => changeDate(val)}
                        ></RangePicker>
                    </Item>
                    <Item label="备注说明">
                        {!isApply ? (
                            <span className={style.remark}>
                                <EmptyPlaceHolder value={pageModel.remark} />
                            </span>
                        ) : (
                            <LimitInput
                                rows={4}
                                disabled={!isApply}
                                title={!isApply ? pageModel.remark : null}
                                value={pageModel.remark}
                                onChange={e => setFieldValue('remark', e.target.value)}
                                maxLength={200}
                                area
                                showNumber
                                placeholder="请输入"
                            />
                        )}
                    </Item>
                    <Form.Item label=" " colon={false}>
                        {getFieldDecorator('table', {
                            initialValue: pageModel.employees,
                            rules: [
                                {
                                    validator(_, value, callback) {
                                        const arr = value.filter(subItem => subItem.isValidatorPass === false);
                                        if (arr?.length > 0) {
                                            callback(' ');
                                        } else {
                                            callback();
                                        }
                                    }
                                }
                            ]
                        })(
                            <ValidatorTable
                                user={user}
                                isApply={isApply}
                                employeeList={employeeList}
                                decimalPlaces={decimalPlaces}
                                onChange={val => setFieldValue('employees', val)}
                            />
                        )}
                    </Form.Item>
                </div>
            </BaseSettingProvider>
        </Spin>
    );
};

export default connect(({ user, finance }) => ({
    user: user.currentUser,
    decimalPlaces: finance.baseSetting?.scale
}))(withRouter(SalaryProcessApply));
